<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="65px"
      >
        <el-form-item label="任务名称" prop="executionPolicyName">
          <common-input
            v-model="queryParams.executionPolicyName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="执行时间" prop="beginTime">
          <el-date-picker
            v-model="dataRange"
            type="datetimerange"
            range-separator="至"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="执行状态" prop="executionStatus">
          <el-select v-model="queryParams.executionStatus">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="执行中" value="1"></el-option>
            <el-option label="执行完成" value="2"></el-option>
            <el-option label="已停止" value="3"></el-option>
          </el-select>
        </el-form-item>
        <!-- <common-dept
          ref="commonDept"
          :currentParent="currentParent"
          @getDeptId="getDeptId"
          @getDeptList="getDeptList"
          @getLoading="getLoading"
        ></common-dept> -->
      </el-form>
    </common-search>
    <common-table slot="content" v-loading="loading" :data="list">
      <el-table-column
        label="任务名称"
        align="left"
        prop="executionPolicyName"
        fixed
        show-overflow-tooltip
      />
      <el-table-column
        label="执行开始时间"
        align="left"
        prop="beginTime"
        width="180"
        show-overflow-tooltip
      />
      <el-table-column
        label="执行结束时间"
        align="left"
        show-overflow-tooltip
        width="180"
      >
        <template slot-scope="scope">
          {{ scope.row.executionStatus === 2 ? scope.row.endTime : "" }}
        </template>
      </el-table-column>
      <el-table-column label="执行状态" align="center" prop="executionStatus">
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.executionStatus === 1"
            size="mini"
            effect="plain"
            :disable-transitions="true"
            >扫描中
          </el-tag>
          <common-table-tooltip :tips="scope.row.executionDetail" v-else>
            <el-tag
              v-if="scope.row.executionStatus === 2"
              size="mini"
              type="success"
              effect="plain"
              :disable-transitions="true"
              >扫描完成
            </el-tag>
            <el-tag
              v-else-if="scope.row.executionStatus === 3"
              size="mini"
              type="danger"
              effect="plain"
              :disable-transitions="true"
              >扫描失败
            </el-tag>
          </common-table-tooltip>
          <!--          <common-table-tooltip :tips="scope.row.executionDetail">-->
          <!--            <el-tag v-if="scope.row.executionStatus === 2" size="mini" type="success" effect="plain">执行完成</el-tag>-->
          <!--          </common-table-tooltip>-->
          <!--          <common-table-tooltip :tips="scope.row.executionDetail">-->
          <!--            <el-tag v-if="scope.row.executionStatus === 3" size="mini" type="danger" effect="plain">已停止</el-tag>-->
          <!--          </common-table-tooltip>-->
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="执行进度"
        align="left"
        prop="speedProgress"
        width="140"
      >
        <template slot-scope="scope">
          <el-progress
            :percentage="scope.row.speedProgress ? scope.row.speedProgress : 0"
            :status="scope.row.speedProgress === 100 ? 'success' : null"
          >
          </el-progress>
        </template>
      </el-table-column> -->

      <!-- <el-table-column
        label="总进度"
        align="center"
        prop="resultDesc"
        width="80"
      >
      </el-table-column> -->
      <el-table-column
        label="执行时长"
        align="left"
        prop="timeDifference"
        show-overflow-tooltip
      />
      <el-table-column
        label="执行人"
        align="left"
        prop="deptName"
        show-overflow-tooltip
      />
      <!-- <el-table-column
        label="组织"
        align="left"
        prop="deptName"
        width="180"
        show-overflow-tooltip
      /> -->

      <el-table-column label="操作" align="left" width="110" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:history:remove']"
            >删除
          </el-button>
          <el-button
            type="text"
            @click="previewReport(scope.row)"
            v-hasPermi="['datascan:executionhistory:querytask']"
          >
            查看报告
          </el-button>
        </template>
      </el-table-column>
    </common-table>
    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <template v-if="isReport">
      <report :report-data="reportData" @close="closeReport"></report>
    </template>
  </common-list>
</template>

<script>
import {
  queryExecutionHistoryListByPage,
  deleteExecutionHistory,
  queryResAuditTaskHistoryById,
} from "@/api/datascan/executionhistory/history";
import { formatDate } from "@/utils";
import CommonList from "@/template/CommonList";
import BaseList from "@/mixins/BaseList";
import Report from "./overview";
import { getSingleArray, getFullDept } from "@/utils/util";

export default {
  name: "History",
  mixins: [BaseList],
  components: {
    CommonList,
    Report,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 执行历史表格数据
      list: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        executionPolicyName: null,
        beginTime: null,
        endTime: null,
        deptIds: null,
        executionStatus: null,
      },
      dataRange: [],
      setInterval: null,
      historyIds: [],
      isReport: false,
      reportData: {
        taskId: null,
        historyId: null,
      },
      currentParent: 4,
      singleDeptList: [],
    };
  },
  created() {
    if (this.$route.query && this.$route.query.executionPolicyName) {
      this.queryParams.executionPolicyName =
        this.$route.query.executionPolicyName;
      this.getList();
    } else {
      this.getList();
    }
  },
  destroyed() {
    this.clearInterval();
  },
  methods: {
    getLoading() {
      this.loading = true;
    },
    // getDeptList(list) {
    //   this.singleDeptList = getSingleArray(list);
    //   this.getList();
    // },
    getDeptId(val) {
      this.queryParams.deptIds = val;
    },
    getDeptName(val) {
      let dept = this.singleDeptList.find((item) => item.id === val.toString());
      if (dept) return getFullDept(dept.fulllabel);
    },
    /** 查询执行历史列表 */
    getList() {
      let that = this;
      this.loading = true;
      queryExecutionHistoryListByPage(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.data.dataList.reduce((r, c) => {
              r.push({
                ...c,
                beginTime: formatDate(c.beginTime),
                endTime: formatDate(c.endTime),
                // timeDifference: that.formatDuring(new Date(c.endTime).getTime() - new Date(c.beginTime).getTime())
                timeDifference: that.formatDuring(c.exeDuration),
                deptName: that.getDeptName(c.deptId || ""),
              });
              return r;
            }, []);
            this.total = res.data.totalCount;
            this.historyIds = [];
            if (this.list && this.list.length) {
              this.list.map((v) => {
                if (!v.speedProgress || v.speedProgress < 100) {
                  this.historyIds.push(v.historyId);
                }
              });

              if (this.historyIds.length) {
                this.clearInterval();
                this.setInterval = setInterval(() => {
                  this.queryResAuditTaskHistoryById();
                }, 5000);
              }
            }
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },

    clearInterval() {
      if (this.setInterval) {
        clearInterval(this.setInterval);
        this.setInterval = null;
      }
    },

    handleInterval() {},

    formatDuring(mss) {
      let days = parseInt(mss / (1000 * 60 * 60 * 24));
      let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
      let seconds = (mss % (1000 * 60)) / 1000;
      return (
        (days ? days + " 天 " : "") +
        (hours ? hours + " 小时 " : "") +
        (minutes ? minutes + " 分钟 " : "") +
        Math.round(seconds) +
        " 秒 "
      );
    },
    queryResAuditTaskHistoryById() {
      let that = this;
      let formData = new FormData();

      if (this.historyIds && this.historyIds.length) {
        this.historyIds.forEach((id) => {
          formData.append("historyIds", id);
        });
      } else {
        return;
      }
      queryResAuditTaskHistoryById(formData)
        .then((res) => {
          if (res && res.code === 200) {
            let nowHistory = res.data.reduce((r, c) => {
              r.push({
                ...c,
                beginTime: formatDate(c.beginTime),
                endTime: formatDate(c.endTime),
                // timeDifference: that.formatDuring(new Date(c.endTime).getTime() - new Date(c.beginTime).getTime())
                timeDifference: that.formatDuring(c.exeDuration),
                deptName: that.getDeptName(c.deptId || ""),
              });
              return r;
            }, []);
            if (nowHistory && nowHistory.length) {
              let delHistoryId = [];
              for (let i = this.list.length - 1; i >= 0; i--) {
                nowHistory.map((value) => {
                  const resultDesc =
                    value.resultDesc &&
                    value.resultDesc.split("/") &&
                    value.resultDesc.split("/").length
                      ? value.resultDesc.split("/")
                      : [1, 2];
                  if (this.list[i].historyId === value.historyId) {
                    this.list.splice(i, 1, value);
                  }
                  if (
                    value.speedProgress === 100 &&
                    value.executionDetail &&
                    resultDesc[0] === resultDesc[1]
                  ) {
                    console.log(value.executionDetail);
                    delHistoryId.push(value.historyId);
                  }
                });
              }
              // this.list.map((v, i) => {
              //   nowHistory.map(value => {
              //     if (v.historyId === value.historyId) {
              //       this.list.splice(i, 1, value)
              //     }
              //     if (value.speedProgress === 100) {
              //       delHistoryId.push(value.historyId)
              //     }
              //   })
              // })
              if (delHistoryId && delHistoryId.length) {
                for (let i = delHistoryId.length - 1; i >= 0; i--) {
                  for (let j = this.historyIds.length - 1; j >= 0; j--) {
                    if (delHistoryId[i] === this.historyIds[j]) {
                      this.historyIds.splice(j, 1);
                    }
                  }
                }
                // delHistoryId.map(v => {
                //   this.historyIds.remove(v)
                // })
              }
            } else {
              clearInterval(this.setInterval);
            }
          } else {
            clearInterval(this.setInterval);
            this.$GlobalErrorConfirm("数据加载失败", res.msg);
          }
        })
        .finally(() => {});
    },

    /** 查询按钮操作 */
    handleQuery() {
      if (this.dataRange && this.dataRange.length) {
        this.queryParams.beginTime = this.dataRange[0];
        this.queryParams.endTime = this.dataRange[1];
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }

      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dataRange = [];
      this.queryParams = this.$options.data().queryParams;
      this.$refs.commonDept.clearDept();
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const historyIds = row.historyId;

      this.$GlobalDeleteConfirm()
        .then(() => {
          deleteExecutionHistory({ historyIds }).then((res) => {
            if (res && res.code == 200) {
              this.queryParams.pageNum = 1;
              this.getList();
              this.$GlobalSuccessMessage("删除成功");
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    previewReport(row) {
      let { taskId, historyId } = row;
      this.reportData.taskId = taskId;
      this.reportData.historyId = historyId;
      this.isReport = true;
    },
    closeReport() {
      this.isReport = false;
    },
  },
};
</script>
